using MediatR;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Write.Api.Application.Command.Payment;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace SmartHealthcare.Write.Api.Application.Handler.Payment
{
    /// <summary>
    /// 更新支付凭证处理器
    /// </summary>
    public class UpdatePaymentReceiptHandler : IRequestHandler<UpdatePaymentReceiptCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<PaymentRecordModel> paymentRepository;
        private readonly ILogger<UpdatePaymentReceiptHandler> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="paymentRepository">支付记录仓储</param>
        /// <param name="logger">日志记录器</param>
        public UpdatePaymentReceiptHandler(
            IBaseRepository<PaymentRecordModel> paymentRepository,
            ILogger<UpdatePaymentReceiptHandler> logger)
        {
            this.paymentRepository = paymentRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 处理更新支付凭证请求
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public Task<APIResult<bool>> Handle(UpdatePaymentReceiptCommand request, CancellationToken cancellationToken)
        {
            APIResult<bool> result = new APIResult<bool>();

            try
            {
                logger.LogInformation($"开始更新支付凭证，支付记录ID：{request.Id}，凭证URL：{request.ReceiptUrl}");

                // 获取支付记录
                var paymentRecord = paymentRepository.GetModel(request.Id);

                if (paymentRecord == null || paymentRecord.IsDeleted)
                {
                    logger.LogWarning($"支付记录不存在，ID：{request.Id}");
                    result.Code = APIEnums.Error;
                    result.Msg = "支付记录不存在";
                    return Task.FromResult(result);
                }

                // 更新凭证URL
                paymentRecord.ReceiptUrl = request.ReceiptUrl;
                
                // 如果提供了操作人员，更新操作人员
                if (!string.IsNullOrEmpty(request.OperatorName))
                {
                    paymentRecord.OperatorName = request.OperatorName;
                }

                // 保存更新
                paymentRepository.Update(paymentRecord);

                logger.LogInformation($"支付凭证更新成功，支付记录ID：{paymentRecord.Id}");

                result.Data = true;
                result.Code = APIEnums.Success;
                result.Msg = "更新支付凭证成功";
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"更新支付凭证时发生异常，支付记录ID：{request.Id}");
                result.Code = APIEnums.Error;
                result.Msg = $"更新支付凭证失败：{ex.Message}";
                result.Data = false;
            }

            return Task.FromResult(result);
        }
    }
} 